package com.qingcloud.fexecutor.base.handler;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.qingcloud.base.pojo.ApiResult;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.core.interceptor.ResultProvider;
import org.ssssssss.magicapi.modules.db.model.Page;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 默认结果封装实现
 */
@Component
public class HttpResultProvider implements ResultProvider {

    @Override
    public Object buildResult(RequestEntity requestEntity, int code, String message, Object data) {
        long timestamp = System.currentTimeMillis();

        ResultJsonBean jsonBean = new ResultJsonBean();
        jsonBean.setMessage(message);
        jsonBean.setData(data);
        jsonBean.setCode(code);
        jsonBean.setFinishTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp));
        jsonBean.setExecuteTime((int) (timestamp - requestEntity.getRequestTime()));
        jsonBean.setRequestTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(requestEntity.getRequestTime()));
        return jsonBean;
    }

    /**
     * 定义分页返回结果，该项会被封装在Json结果内，
     * 此方法可以不覆盖，默认返回PageResult
     */
    @Override
    public Object buildPageResult(RequestEntity requestEntity, Page page, long total, List<Map<String, Object>> data) {
        return new HashMap<String, Object>() {
            {
                put("count", total);
                put("data", data);
            }
        };
    }

    /**
     * 异常封装
     */
    @Override
    public Object buildException(RequestEntity requestEntity, Throwable throwable) {
        ApiResult apiResult = new ApiResult();
        apiResult.setCode(500);
        apiResult.setError("系统错误");
        apiResult.setTrace(ExceptionUtil.stacktraceToString(throwable));
        return apiResult;
    }

}
